// CodeGraph API服务
// 提供代码图谱构建、查询、分析等功能

import { apiClient, RequestConfig } from './ApiClient';

// CodeGraph相关类型
export interface GraphInitResult {
  graphId: string;
  workspace: string;
  status: 'initializing' | 'ready' | 'error';
  progress: number;
  message?: string;
}

export interface GraphNode {
  id: string;
  nodeType: string;
  name: string;
  filePath: string;
  startLine: number;
  endLine: number;
  properties: Record<string, any>;
  metadata: NodeMetadata;
}

export interface GraphEdge {
  id: string;
  source: string;
  target: string;
  edgeType: string;
  properties: Record<string, any>;
  weight?: number;
}

export interface NodeMetadata {
  language: string;
  visibility: string;
  complexity?: number;
  size?: number;
  dependencies?: string[];
}

export interface GraphQuery {
  nodeTypes?: string[];
  edgeTypes?: string[];
  filters?: QueryFilter[];
  limit?: number;
  offset?: number;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

export interface QueryFilter {
  field: string;
  operator: 'eq' | 'ne' | 'gt' | 'lt' | 'gte' | 'lte' | 'in' | 'contains';
  value: any;
}

export interface QueryResult {
  nodes: GraphNode[];
  edges: GraphEdge[];
  totalNodes: number;
  totalEdges: number;
  executionTime: number;
  query: GraphQuery;
}

export interface GraphStats {
  totalNodes: number;
  totalEdges: number;
  nodesByType: Record<string, number>;
  edgesByType: Record<string, number>;
  languageDistribution: Record<string, number>;
  complexity: {
    average: number;
    max: number;
    min: number;
  };
  lastUpdated: string;
}

export interface DependencyInfo {
  source: string;
  target: string;
  type: 'import' | 'call' | 'inheritance' | 'composition' | 'reference';
  strength: number;
  filePath: string;
  line: number;
}

export interface PathResult {
  path: GraphNode[];
  edges: GraphEdge[];
  distance: number;
  weight: number;
}

// CodeGraph API类
export class CodeGraphApi {
  // 初始化代码图谱
  async initializeGraph(
    workspace: string,
    options?: {
      languages?: string[];
      includeTests?: boolean;
      maxDepth?: number;
    },
    config?: RequestConfig
  ): Promise<GraphInitResult> {
    return apiClient.invoke<GraphInitResult>(
      'initialize_codegraph',
      { workspace, options },
      {
        ...config,
        timeout: 120000, // 2分钟超时
      }
    );
  }

  // 更新代码图谱
  async updateGraph(
    graphId: string,
    filePaths?: string[],
    config?: RequestConfig
  ): Promise<GraphInitResult> {
    return apiClient.invoke<GraphInitResult>(
      'update_codegraph',
      { graphId, filePaths },
      config
    );
  }

  // 查询图谱
  async queryGraph(
    query: GraphQuery,
    config?: RequestConfig
  ): Promise<QueryResult> {
    return apiClient.invoke<QueryResult>(
      'query_graph',
      { query },
      {
        ...config,
        cache: true,
        cacheKey: `query:${JSON.stringify(query)}`,
        cacheTTL: 60000, // 1分钟缓存
      }
    );
  }

  // 获取图谱统计信息
  async getGraphStats(
    graphId?: string,
    config?: RequestConfig
  ): Promise<GraphStats> {
    return apiClient.invoke<GraphStats>(
      'get_graph_stats',
      { graphId },
      {
        ...config,
        cache: true,
        cacheKey: `stats:${graphId || 'default'}`,
        cacheTTL: 300000, // 5分钟缓存
      }
    );
  }

  // 获取节点详情
  async getNodeDetails(
    nodeId: string,
    config?: RequestConfig
  ): Promise<GraphNode> {
    return apiClient.invoke<GraphNode>(
      'get_node_details',
      { nodeId },
      {
        ...config,
        cache: true,
        cacheKey: `node:${nodeId}`,
        cacheTTL: 300000, // 5分钟缓存
      }
    );
  }

  // 获取节点关系
  async getNodeRelations(
    nodeId: string,
    direction: 'incoming' | 'outgoing' | 'both' = 'both',
    maxDepth: number = 1,
    config?: RequestConfig
  ): Promise<{
    nodes: GraphNode[];
    edges: GraphEdge[];
  }> {
    return apiClient.invoke(
      'get_node_relations',
      { nodeId, direction, maxDepth },
      {
        ...config,
        cache: true,
        cacheKey: `relations:${nodeId}:${direction}:${maxDepth}`,
        cacheTTL: 300000, // 5分钟缓存
      }
    );
  }

  // 查找路径
  async findPath(
    sourceId: string,
    targetId: string,
    maxDepth: number = 5,
    config?: RequestConfig
  ): Promise<PathResult[]> {
    return apiClient.invoke<PathResult[]>(
      'find_path',
      { sourceId, targetId, maxDepth },
      config
    );
  }

  // 获取依赖关系
  async getDependencies(
    filePath: string,
    config?: RequestConfig
  ): Promise<DependencyInfo[]> {
    return apiClient.invoke<DependencyInfo[]>(
      'get_dependencies',
      { filePath },
      {
        ...config,
        cache: true,
        cacheKey: `deps:${filePath}`,
        cacheTTL: 300000, // 5分钟缓存
      }
    );
  }

  // 获取影响分析
  async getImpactAnalysis(
    nodeId: string,
    config?: RequestConfig
  ): Promise<{
    directImpact: GraphNode[];
    indirectImpact: GraphNode[];
    riskLevel: 'low' | 'medium' | 'high';
    affectedFiles: string[];
  }> {
    return apiClient.invoke(
      'get_impact_analysis',
      { nodeId },
      config
    );
  }

  // 搜索节点
  async searchNodes(
    query: string,
    filters?: {
      nodeTypes?: string[];
      languages?: string[];
      filePaths?: string[];
    },
    config?: RequestConfig
  ): Promise<GraphNode[]> {
    return apiClient.invoke<GraphNode[]>(
      'search_nodes',
      { query, filters },
      config
    );
  }

  // 获取热点分析
  async getHotspots(
    metric: 'complexity' | 'dependencies' | 'changes' | 'size',
    limit: number = 10,
    config?: RequestConfig
  ): Promise<Array<{
    node: GraphNode;
    score: number;
    rank: number;
  }>> {
    return apiClient.invoke(
      'get_hotspots',
      { metric, limit },
      {
        ...config,
        cache: true,
        cacheKey: `hotspots:${metric}:${limit}`,
        cacheTTL: 600000, // 10分钟缓存
      }
    );
  }

  // 导出图谱
  async exportGraph(
    format: 'json' | 'graphml' | 'dot' | 'csv',
    options?: {
      includeMetadata?: boolean;
      nodeTypes?: string[];
      edgeTypes?: string[];
    },
    config?: RequestConfig
  ): Promise<string> {
    return apiClient.invoke<string>(
      'export_graph',
      { format, options },
      {
        ...config,
        timeout: 60000, // 1分钟超时
      }
    );
  }

  // 导入图谱
  async importGraph(
    data: string,
    format: 'json' | 'graphml',
    config?: RequestConfig
  ): Promise<GraphInitResult> {
    return apiClient.invoke<GraphInitResult>(
      'import_graph',
      { data, format },
      {
        ...config,
        timeout: 120000, // 2分钟超时
      }
    );
  }

  // 监听图谱更新事件
  async onGraphUpdate(
    callback: (update: {
      type: 'node_added' | 'node_updated' | 'node_removed' | 'edge_added' | 'edge_updated' | 'edge_removed';
      data: GraphNode | GraphEdge;
      timestamp: string;
    }) => void
  ): Promise<() => void> {
    return apiClient.listen('graph-update', callback);
  }

  // 监听构建进度
  async onBuildProgress(
    callback: (progress: {
      stage: string;
      progress: number;
      message: string;
      timestamp: string;
    }) => void
  ): Promise<() => void> {
    return apiClient.listen('build-progress', callback);
  }

  // 获取构建状态
  async getBuildStatus(
    graphId?: string,
    config?: RequestConfig
  ): Promise<{
    status: 'idle' | 'building' | 'updating' | 'error';
    progress: number;
    stage: string;
    message?: string;
    startTime?: string;
    estimatedCompletion?: string;
  }> {
    return apiClient.invoke(
      'get_build_status',
      { graphId },
      config
    );
  }

  // 取消构建
  async cancelBuild(
    graphId?: string,
    config?: RequestConfig
  ): Promise<boolean> {
    return apiClient.invoke<boolean>(
      'cancel_build',
      { graphId },
      config
    );
  }
}

// 全局CodeGraph API实例
export const codeGraphApi = new CodeGraphApi();

// 导出类型
export type {
  GraphInitResult,
  GraphNode,
  GraphEdge,
  NodeMetadata,
  GraphQuery,
  QueryFilter,
  QueryResult,
  GraphStats,
  DependencyInfo,
  PathResult,
};
